import axios from 'axios'
import {Message, MessageBox} from 'element-ui'
import {getToken, removeToken} from '@/utils/auth'
import router from "@/routers";
// import process from "shelljs";
// 创建axios实例
const service = axios.create({
    baseURL: 'http://localhost:8002/api/', // api的base_url
    timeout: 15000, // 请求超时时间
});

// request拦截器
service.interceptors.request.use(config => {
    let token = getToken();
    if (token !== null) {
        config.headers['Authorization'] = token; // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config
}, error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
    response => {
        /**
         * code为非200是抛错 可结合自己业务进行修改
         */
        const res = response.data;
        if (res.code !== 200) {
            // 401:未登录;
            if (res.code === 401) {
                removeToken()
                MessageBox.confirm(res.message, '验证失败', {
                    confirmButtonText: '重新登录',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    router.push("/login")
                    // location.reload()// 为了重新实例化vue-router对象 避免bug
                })
            } else {
                Message({
                    message: res.message,
                    type: 'error',
                    duration: 3 * 1000
                })
                return Promise.reject('error')
            }

        } else {
            return response.data
        }
    },
    error => {
        if (error.response.status === 403) {
            Message({
                message: "权限不足或未登录，请登陆后重试",
                type: 'error',
                duration: 3 * 1000
            })
            router.push("/login")
            location.reload()// 为了重新实例化vue-router对象 避免bug
        }
        if (error.response.status === 500) {
            Message({
                message: "服务器走神啦",
                type: 'error',
                duration: 3 * 1000
            })
        }
        return new Promise.reject('error');
    }
)

export default service
